<template>
	<view class="">
		<view v-if="formData.status == 2" class="text-center padding color-red">
			您的上报异常正在审核，请耐心等待！
		</view>
		<uv-form labelPosition="left" labelWidth="120" :model="formData" :rules="rules" ref="form">
			<view class="bg-white padding-lr">
				<!-- <uv-form-item label="原开始时间" prop="" borderBottom>
					<view class="text-gray">
						{{formData.startTime}}
					</view>
				</uv-form-item> -->
				<uv-form-item label="推荐作业时间" prop="" borderBottom>
					<view class="text-gray">
						{{formData.endTime}}
					</view>
				</uv-form-item>
				<uv-form-item label="异常类型" prop="typeName" borderBottom @click="showTypeSelect">
					<uv-input v-model="formData.typeName" disabled disabledColor="#ffffff" placeholder="请选择异常类型"
						border="none">
					</uv-input>
					<template v-slot:right>
						<uv-icon name="arrow-right"></uv-icon>
					</template>
				</uv-form-item>
				<uv-form-item v-if="formData.type != 2" label="延长结束时间" prop="delayTime" borderBottom @click="openTime">
					<uv-input v-model="formData.delayTime" disabled disabledColor="#ffffff" placeholder="请选择时间"
						border="none">
					</uv-input>
					<template v-slot:right>
						<uv-icon name="arrow-right"></uv-icon>
					</template>
				</uv-form-item>
				<uv-form-item label="异常原因" prop="delayReason" borderBottom>
					<uv-textarea :disabled="!isEdit" :maxlength="-1" autoHeight v-model="formData.delayReason"
						border="none">
					</uv-textarea>
				</uv-form-item>
				<uv-form-item v-if="formData.type != 2" label="附件上传(最多3张)" prop="image" labelWidth="160"
					labelPosition="top">
					<view class="margin-top-sm">
						<ImageUpload :disabled="!isEdit" :deletable="isEdit" v-model="formData.image" />
					</view>
				</uv-form-item>

				<view class="text-center color-red padding" v-if="isEdit">
					请与订单户主沟通确认一致后再提交，以确保订单 的有序进行！
				</view>
			</view>
			<view class="bg-white padding-lr margin-top" v-if="!isEdit">
				<!-- <uv-form labelPosition="left" labelWidth="120"> -->
				<uv-form-item label="申请状态" prop="status" borderBottom>
					<view class="text-red">
						{{selectDictLabel(auditStatus, formData.status)}}
					</view>
				</uv-form-item>
				<template v-if="formData.status == 0 || formData.status == 1">
					<uv-form-item label="审核意见" prop="auditReason" borderBottom>
						<view class="">
							{{ formData.auditReason || '' }}
						</view>
					</uv-form-item>
					<uv-form-item label="审核时间" prop="exceptionTime" borderBottom>
						<view class="">
							{{formData.exceptionTime || ''}}
						</view>
					</uv-form-item>
				</template>
			</view>
		</uv-form>
		<uv-action-sheet ref="typeSelect" :actions="actions" title="请选择异常类型" @select="typeConfirm">
		</uv-action-sheet>

		<uv-datetime-picker ref="datetimePicker" :minDate="minDate" :maxDate="1786778555000" v-model="dateValue"
			mode="datetime" :formatter="formatter" @confirm="confirmTime">
		</uv-datetime-picker>

		<view class="foot-box">
			<template>
				<button class="cu-btn flex-sub margin-right-sm" :class="theme == 'fs'? 'bg-main': 'bg-green'"
					@click="goBack">返回</button>
				<button class="cu-btn flex-sub margin-right-sm" :class="theme == 'fs'? 'bg-main': 'bg-green'"
					v-if="formData.status == 2|| formData.status == '4'" @click="onCancel">取消</button>
				<template v-if="isEdit">
					<button class="cu-btn flex-sub margin-right-sm"
						v-if="formData.status == null || formData.status == 4 || formData.status == '2'"
						@click="submitPre">暂存</button>
					<button class="cu-btn flex-sub" :class="theme == 'fs'? 'bg-main': 'bg-green'"
						v-if="formData.status == null || formData.status == '4' || formData.status == '2'|| formData.status == '1'"
						@click="submit">提交</button>
				</template>
			</template>
		</view>
	</view>
</template>
<script>
	import ImageUpload from '@/components/imageUpload/index.vue'
	import {
		selectDictLabel
	} from '@/utils/huida.js'
	import {
		mapGetters
	} from 'vuex'

	export default {
		// dicts: ['order_exc_type '],
		components: {
			ImageUpload
		},
		computed: {
			...mapGetters(['theme'])
		},
		data() {
			return {
				minDate: Date.now(),
				formData: {
					startTime: '',
					endTime: '',
					type: '',
					typeName: '',
					delayTime: '',
					delayReason: '',
					image: '',
				},
				dateValue: Number(new Date()),
				actions: [],
				rules: {
					typeName: {
						type: 'string',
						required: true,
						message: '请选择异常类型',
						trigger: ['blur', 'change']
					},
					delayTime: {
						type: 'string',
						required: true,
						message: '请选择延期时间',
						trigger: ['blur', 'change']
					},
					image: {
						type: 'string',
						required: true,
						message: '请上传照片',
						trigger: ['blur', 'change']
					}
				},
				id: '',
				orderLogId: '',
				expId: '',
				isEdit: true,
				auditStatus: [],
				isTemporarily: ''
			}
		},
		// computed: {
		// 	actions() {
		// 		return this.dict.type.order_exc_type?.map(item => ({
		// 			name: item.dictLabel,
		// 			value: item.dictValue 
		// 		}))
		// 	}
		// },
		onLoad(data) {
			if (this.theme == 'farmer') {
				uni.setNavigationBarColor({
					backgroundColor: '#0BCA89',
					frontColor: '#ffffff',
					success(res) {
						console.log('success', res)
					},
					fail(err) {
						console.log('err123', err)
					}
				});
			}
			this.id = data.id
			this.orderLogId = data.orderLogId
			this.formData.startTime = data.homeworkStartTime
			this.formData.endTime = data.dockingPeopleTime
			this.expId = data.expId
			this.isEdit = data.isEdit == "true" ? true : false
			uni.$uv.http.get('/system/dict/data/type/order_exc_type').then(res => {
				this.actions = res.data.map(item => ({
					name: item.dictLabel,
					label: item.dictLabel,
					value: item.dictValue
				}))
				if (data.expId) {
					this.fetchDetail()
				}
			})
			uni.$uv.http.get('/system/dict/data/type/audit_status').then(res => {
				this.auditStatus = res.data.map(item => ({
					label: item.dictLabel,
					value: item.dictValue
				}))
			})

		},
		methods: {
			selectDictLabel,
			goBack() {
				uni.navigateBack()
			},
			// 详情
			fetchDetail() {
				this.$http.get(`/cadre/orderException/getDatail/${this.expId}`).then(res => {
					res.data.typeName = selectDictLabel(this.actions, res.data.type)
					this.formData = res.data

				})
			},
			// 取消
			onCancel() {
				let that = this
				uni.showModal({
					title: '提示',
					content: '确定取消该记录？',
					success: function(res) {
						if (res.confirm) {
							that.$http.get(`/cadre/orderException/cancel/${that.expId}`).then(res => {
								uni.showToast({
									title: '取消成功'
								})
								that.goBack()
							})
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				});

			},
			// 暂存
			submitPre() {
				this.formData.isTemporarily = 1;
				const payload = {
					orderId: this.id,
					orderLogId: this.orderLogId,
					...this.formData,
					status: 4,
					exceptionType: this.theme == 'farmer' ? '1' : '2'
				}
				this.$refs.form.validate().then(res => {
					uni.showLoading()
					this.$http.post('/cadre/orderException/add', payload)
						.then(res => {
							uni.hideLoading()
							if (res.code != 200) return uni.showToast({
								icon: 'none',
								title: res.msg
							})
							uni.showToast({
								icon: 'success',
								title: '暂存成功',
								duration: 1500,
								complete: () => {
									uni.navigateBack();
								}
							})
						})
				})
			},
			// 提交
			submit() {
				this.formData.isTemporarily = 0;
				// 如果有错误，会在catch中返回报错信息数组，校验通过则在then中返回true
				this.$refs.form.validate().then(res => {
					uni.showLoading()
					this.$http.post('/cadre/orderException/add', {
						orderId: this.id,
						orderLogId: this.orderLogId,
						...this.formData,
						status: 2,
						exceptionType: this.theme == 'farmer' ? '1' : '2'
					}).then(res => {
						uni.hideLoading()
						if (res.code != 200) return uni.showToast({
							icon: 'none',
							title: res.msg
						})
						uni.navigateBack()
					})
				}).catch(errors => {
					uni.hideLoading()
					// uni.showToast({
					// 	icon: 'error',
					// 	title: '请检查输入项是否完整'
					// })
				})
			},
			// 重置
			reset() {
				this.$refs.form.resetFields();
				this.$refs.form.clearValidate();
			},
			openTime() {
				if (!this.isEdit) return
				this.$refs.datetimePicker.open();
			},
			confirmTime(e) {
				console.log(e)
				this.formData.delayTime = uni.$uv.timeFormat(e.value, 'yyyy-mm-dd hh') + ':00:00'
				// console.log(this.formData.delayTime)
			},
			formatter(type, value) {
				if (type === 'year') {
					return `${value}年`
				}
				if (type === 'month') {
					return `${value}月`
				}
				if (type === 'day') {
					return `${value}日`
				}
				if (type === 'hour') {
					return `${value}时`
				}
				return '00分'
			},
			// 类型选择
			showTypeSelect() {
				if (!this.isEdit) return
				this.$refs.typeSelect.open();
				this.hideKeyboard();
			},
			// 类型选择返回结果
			typeConfirm(e) {
				this.formData.type = e.value
				this.formData.typeName = e.name
			},
			hideKeyboard() {
				uni.hideKeyboard()
			},
		}
	}
</script>

<style lang="scss" scoped>
	.foot-box {
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 20rpx;
		background-color: #fff;
	}

	.color-red {
		color: #FE3A6A;
	}
</style>